package com.weixing.mall.core.support.upload;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.PutObjectResult;
import com.weixing.mall.core.properties.ali.OssProperties;

import java.io.InputStream;

/**
 * @Author: kfc
 * @Description: <br/>
 * Date:Create in 2019/8/22 10:53
 * @Modified By:
 */
public class AliOssUpload {

    private OssProperties ossProperties;

    public AliOssUpload(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    /**
     * 创建存储空间
     *
     * @param bucketName
     */
    public Bucket createBucket(String bucketName) {
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = initClient(this.ossProperties);
            // 创建存储空间。
            return ossClient.createBucket(bucketName);
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            if (null != ossClient) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    /**
     * 文件流的方式上传文件
     *
     * @param bucketName  存储空间
     * @param key  文件标识
     * @param is   文件流
     */
    public boolean upload(String bucketName, String key, InputStream is) {
        OSS ossClient = null;
        try {
            ossClient = initClient(this.ossProperties);
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, is);
            return true;
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            if (null != ossClient) {
                ossClient.shutdown();
            }
        }
        return false;
    }

    /**
     * 删除图片
     *
     * @param bucketName  存储空间
     * @param objectName  文件名
     * @return
     */
    public boolean delete(String bucketName,String objectName){
        OSS ossClient = null;
        try {
            ossClient = initClient(this.ossProperties);
            ossClient.deleteObject(bucketName, objectName);
           return true;
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            if (null != ossClient) {
                ossClient.shutdown();
            }
        }
        return false;
    }

    private OSS initClient(OssProperties ossProperties){
        return new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
    }


}
